package Sokoban::Handy;
use 5.014002;
use Carp;
use Data::Dump qw(dump);
use base 'Exporter';
our %SEEN;
our %TAHY;
our %INVALID;
our %MOVES;
our @POKR;
our %EXPORT_TAGS = (
    'all' => [
        qw(@POKR %SEEN %TAHY %INVALID %MOVES minmax setinvalid tothree strcas isempty isnotempty pozice replace boxply without)
    ]
);
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );

sub pozice {
    my( $box, $ply ) = @_;
    my $s = pack 'W*', ( @{$box}, $ply );

    return $s;
}

sub boxply {
    my($pozice) = @_;
    my( @box, $ply );
    @box = unpack 'W*', $pozice;
    $ply = pop @box;
    return ( [@box], $ply );
}

sub replace {
    my( $box, $source, $target ) = @_;
    return [ sort { $a <=> $b } map { $_ == $source ? $target : $_ } values $box ];
}


sub minmax (@) {
    return unless @_;
    my $min = my $max = $_[0];
    for(@_) {
        $min = $_ if $_ < $min;
        $max = $_ if $_ > $max;
    }

    return ($min, $max);
}


sub setinvalid {
    my($pozice) = @_;
    $INVALID{$pozice} = 1;
    delete $TAHY{$pozice};
    delete $SEEN{$pozice};
    return;
}

sub tothree {
    use integer;
    my($cislo) = @_;
    $cislo = sprintf "%d", $cislo;
    my( $delka, $nasobek, $zbytek, $mustr );
    $delka   = length $cislo;
    $nasobek = $delka / 3;
    $zbytek  = $delka % 3;
    $mustr   = "a$zbytek" . ( 'a3' x $nasobek );
    return sprintf "%12s", join " ", unpack $mustr, $cislo;
}

sub strcas {
    my($cas) = @_;
    $cas = sprintf '%.2f', $cas;
    use integer;
    my @parts;
    my( $sec, $mili ) = split /\./, $cas;
    $sec = int $sec;
    push @parts, $sec / 3600;
    $sec = $sec % 3600;
    push @parts, $sec / 60;
    push @parts, $sec % 60;
    return sprintf "%15s", join( ':', map { sprintf '%02d', $_ } @parts ) . sprintf( ".%02d", $mili );
}

sub isempty {
    my($x) = @_;
    confess 'isempty: $x is not defined' unless defined $x;
    confess '$x is not ARRAY ref' unless ref($x) eq 'ARRAY';
    return 1 if $x ~~ [];
    return '';
}

sub isnotempty {
    my($x) = @_;
    return !isempty($x);
}

1;
